package com.ls.controller.interceptor;

import com.ls.entity.User;
import com.ls.service.MessageService;
import com.ls.util.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 消息拦截器
 *
 * @author ls
 * @date 2021/1/31
 **/
@Component
public class MessageInterceptor implements HandlerInterceptor {

    @Autowired
    UserContextHolder userContextHolder;

    @Autowired
    MessageService messageService;

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = userContextHolder.getUser();
        if (user != null && modelAndView != null) {
            int letterUnreadCount = messageService.queryLetterUnreadCount(user.getId(), null);
            int noticeUnreadCount = messageService.queryNoticeUnreadCount(user.getId(), null);
            modelAndView.addObject("unreadCount", letterUnreadCount + noticeUnreadCount);
        }
    }
}
